<template>
  <div class="main1">
    <div class="searchBox">
      <Search :companyData="companyData"  :initData="initSearchData" @emitSearchData="getSearchData"></Search>
    </div>
    <div class="app-amin">
      <div class="main" ref="chart"></div>
      <div class="big-main" ref="lianechart"></div>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import * as echarts from "echarts";
import Search from "./components/search";
import { colorList } from "@/unit/echartsColor";
import api from "@/server/ncCheckConfig";

function getRangeTime(value) {
  switch (value) {
    case 0:
      return [
        moment()
          .quarter(moment().quarter())
          .startOf("quarter"),
        moment()
          .quarter(moment().quarter())
          .endOf("quarter")
      ];
    case 1:
      return [
        moment()
          .quarter(moment().quarter() - 1)
          .startOf("quarter"),
        moment()
          .quarter(moment().quarter() - 1)
          .endOf("quarter")
      ];
    case 2:
      return [
        moment()
          .year(moment().year())
          .startOf("year"),
        moment()
          .year(moment().year())
          .endOf("year")
      ];
    case 3:
      return [
        moment()
          .year(moment().year() - 1)
          .startOf("year"),
        moment()
          .year(moment().year() - 1)
          .endOf("year")
      ];
    case 4:
      return [moment(), moment()];
    default:
      break;
  }
}

export default {
  name: "MyData",
  components: {
    Search
  },
  data() {
    return {
      companyData: [],
      dateRange: [],
      pickerOptions: {
        disabledDate: time => {
          const userSelectedStartDate = new Date(this.dateRange[0]);
          const oneYearAgo = new Date(userSelectedStartDate);
          oneYearAgo.setFullYear(userSelectedStartDate.getFullYear() - 1);
          const oneYearLater = new Date(userSelectedStartDate);
          oneYearLater.setFullYear(userSelectedStartDate.getFullYear() + 1);
          return (
            time.getTime() < oneYearAgo.getTime() ||
            time.getTime() > oneYearLater.getTime()
          );
        }
      },
      initSearchData: {
        company: '',
        beginTime: `${moment(new Date())
          .subtract(12, "months")
          .format("YYYY-MM")}`,
        endTime: `${moment(new Date()).format("YYYY-MM")}`,
        rangeTime: [
          moment(new Date()).subtract(12, "months"),
          moment(new Date())
        ]
      },
      searchData: {}
    };
  },
  beforeMount() {
    api.findCompany().then(res => {
        if(res.data) {
          this.companyData = res.data
          // this.company = res.data[0]
          this.initSearchData.company = res.data[0]
          
        }
      })
      .then(res => {
        this.searchData = this.initSearchData;
    this.getPieData(this.searchData)
    this.getLineData(this.searchData)
      })
  },
  mounted() {
    // this.searchData = this.initSearchData;
    // this.getPieData(this.searchData)
    // this.getLineData(this.searchData)
    // this.setDefaultDateRange();
    // this.echartsInit();
    // this.linechartInit();
  },
  methods: {
    getPieData(timer) {
      let beginTime = `${timer.beginTime}-01 00:00:00`
      let thisMonthDays = moment(timer.endTime, "YYYY-MM").daysInMonth()
      let endTime = `${timer.endTime}-${thisMonthDays} 23:59:59`
      let company = timer.company
      let data = {
        company: company,
        beginTime: beginTime,
        endTime: endTime
      }
      api.findStatisticsData(data).then(res => {
        if(res.msgCode == 0) {
          this.echartsInit(res.data)
        }
      });
    },
    getLineData(timer) {
      let beginTime = `${timer.beginTime}-01 00:00:00`
      let thisMonthDays = moment(timer.endTime, "YYYY-MM").daysInMonth()
      let endTime = `${timer.endTime}-${thisMonthDays} 23:59:59`
      let data = {
        beginTime: beginTime,
        endTime: endTime,
        company: this.initSearchData.company,
      }
      api.findTrendChartData(data).then(res => {
        if(res.msgCode == 0) {
          this.linechartInit(res.data)
        }
      });
    },
    getSearchData(value) {
      this.searchData = value;
      this.getPieData(this.searchData);
    },
    setDefaultDateRange() {
      const end = new Date(); // 当前日期
      const start = new Date();
      start.setMonth(start.getMonth() - 12); // 当前日期往前推12个月
      this.dateRange = [start, end];
    },
    generateXAxisData() {
      const { beginTime, endTime } = this.searchData;
      const start = moment(beginTime);
      const end = moment(endTime);
      // 计算月份数组
      const monthsArray = [];
      let current = start.clone();
      while (current.isSameOrBefore(end, "month")) {
        monthsArray.push(current.format("MM"));
        current.add(1, "month");
      }
      return monthsArray;
    },
    echartsInit(pieData) {
      let dataList = []
      let nameList = []
      if(pieData.system) {
        dataList.push({
          name: '数控系统',
          value: pieData.system.totalProduct?pieData.system.totalProduct:0
        })
      }
      if(pieData.HIO) {
        dataList.push({
          name: 'i/o',
          value: pieData.HIO.totalHIO?pieData.HIO.totalHIO:0
        })
      }
      if(pieData.servo) {
        dataList.push({
          name: '伺服驱动',
          value: pieData.servo.totalServo?pieData.servo.totalServo:0
        })
      }
      if(pieData.motor) {
        dataList.push({
          name: '电机',
          value: pieData.motor.totalMotor?pieData.motor.totalMotor:0
        })
      }
      dataList.forEach(item=> {
        nameList.push(item.name)
      })

      const myChart = echarts.init(this.$refs.chart); //初始化容器
      // 饼图数据
      var data = dataList
      // 计算总数
      var total = data.reduce((acc, cur) => acc + cur.value, 0);

      // 饼图配置
      var option = {
        tooltip: {
          trigger: "item", // Set trigger to 'item' for pie chart
          formatter: "{b}: {c} ({d}%)" // Display name, value, and percentage
        },
        title: {
          text: "出货统计"
        },
        color: ['#1890ff', 'rgb(109,183,117)', 'rgb(248,181,81)', 'rgb(42,52,243)'],
        legend: {
          orient: "vertical",
          right: "10%",
          top: "center",
          itemWidth: 10,
          align: "left",
          // bottom: "10%", // Adjust the bottom margin here
          itemHeight: 10,
          formatter: function(name) {
            // 在legend后面添加具体数字
            var value = data.find(item => item.name === name).value;
            return `${name}: ${value}`;
          },
          data: nameList
        },

        series: [
          {
            type: "pie",
            radius: ["50%", "60%"],
            center: ["30%", "50%"],
            avoidLabelOverlap: false,
            label: {
              show: true, // 设置为 true 显示 label
              position: "inside", // 设置 label 位置为外部
              formatter: "{d}%" // 显示百分比
            },
            labelLine: {
              show: false
            },
            data: data.map((item, index) => {
              return {
                value: item.value,
                name: item.name
              };
            })
          },
          {
            name: "中间文字",
            z: 100,
            type: "gauge",
            radius: "-50%",
            center: ["30%", "50%"], // 需和type: 'pie'中的center一致
            // 配置中间的数字的样式
            detail: {
              // 调节数字位置
              offsetCenter: [-1, -10],
              color: "#000"
            },

            pointer: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            },
            splitLine: {
              show: false
            },
            axisLabel: {
              show: false
            },
            // 中间的字和数字 数据
            data: [
              {
                value: `${total}`,
                name: "总数",
                title: {
                  // 配置“家居总数”的样式
                  show: true,
                  offsetCenter: [0, "-20%"]
                }
              }
            ]
          }
        ],
        grid: {
          left: 15,
          right: 10, // 调整右侧空间以容纳图例
          bottom: 0,
          top: 20,
          containLabel: true
        }
      };
      myChart.setOption(option);
    },
    linechartInit(lineData) {
      let dataList = []
      let nameList = []
      if(lineData.macmodel && lineData.macmodel.length > 0) {
        let valueList = []
        lineData.macmodel.forEach(item => {
          valueList.push(item.records)
          nameList.push(item.month)
        })
        dataList.push({
          name: "数控系统",
          value: valueList
        })
      }
      if(lineData.HIO && lineData.HIO.length > 0) {
        let valueList = []
        lineData.HIO.forEach(item => {
          valueList.push(item.records)
        })
        dataList.push({
          name: "i/o",
          value: valueList
        })
      }
      if(lineData.servo && lineData.servo.length > 0) {
        let valueList = []
        lineData.servo.forEach(item => {
          valueList.push(item.records)
        })
        dataList.push({
          name: "伺服驱动",
          value: valueList
        })
      }
      if(lineData.macAxNum && lineData.macAxNum.length > 0) {
        let valueList = []
        lineData.macAxNum.forEach(item => {
          valueList.push(item.records)
        })
        dataList.push({
          name: "电机",
          value: valueList
        })
      }
      const myChart = echarts.init(this.$refs.lianechart); //初始化容器
      const xData = this.generateXAxisData();
      let ListData = dataList
      const series = ListData.map(item => {
        const colorObj = colorList.find(
          colorItem => colorItem.name === item.name
        );
        const color = colorObj ? colorObj.color : "auto"; // 如果找不到对应颜色，则使用 'auto'

        return {
          name: item.name,
          type: "line",
          stack: "Total",
          data: item.value,
          itemStyle: {
            color: color
          }
        };
      });
      // 饼图数据
      let option = {
        title: {
          text: "出货趋势图"
        },
        tooltip: {
          trigger: "axis"
        },
        grid: {
          top: "100" // 上部内边距为20像素
        },
        legend: {
          right: "10%",
          data: ["数控系统", "i/o", "电机", "伺服驱动"]
        },

        xAxis: {
          type: "category",
          boundaryGap: false,
          // data: xData
          data: nameList
        },
        yAxis: {
          type: "value"
        },
        series: series
      };
      myChart.setOption(option);
    }
  }
};
</script>
<style  scoped>
.main1 {
  width: 100%;
  background: #e4e4e4;
  height: 100%;
}
.app-amin {
  width: 100%;
  /* height: 100%; */
  display: flex;
  /* justify-content: space-between; */
}
.main {
  width: 400px;
  margin-left: 15px;
  height: 300px;
  margin-top: 20px;
  background: #fff;
  padding: 10px;
  border-radius: 15px;
}
.big-main {
  /* width: calc(100% - 800px); */
  /* width: 800px; */
  flex: 1;
  /* flex: 1; */
  background: #fff;
  margin-top: 20px;
  margin-left: 10px;
  margin-right: 15px;
  height: 300px;
  border-radius: 15px;
  padding: 10px;
  max-width: 100%; /* 添加这行样式规则 */
}
</style>